package com.sunsys.mapreduce.enumcounter.retrieveInReducer;

import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Reducer;

public class RecordsCountValidationReducer extends Reducer<Text, Text, Text, Text> {

	public RecordsCountValidationReducer() {
	}
	
	@Override
	protected void setup(Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
	}
	
	@Override
	protected void reduce(Text key, Iterable<Text> iterable, Reducer<Text, Text, Text, Text>.Context context)
			throws IOException, InterruptedException {

		String fileName = key.toString();
		Text value = iterable.iterator().next();
		String recordsCountInFooterStr = value.toString();
		
		System.out.println("File name in Reducer:"+fileName);
		
		Counter counter = context.getCounter(RecordsCount.FILE1_COUNTER);
		long recordsCountCounterValue = counter.getValue();
		
		long recordsCountInFooter = Long.parseLong(recordsCountInFooterStr);
		if(recordsCountCounterValue == recordsCountInFooter) {
			context.write(key, new Text("Records matched. Records Count:"+recordsCountCounterValue));
		} else {
			context.write(key, new Text("Records mismatch. Actual records in the file:"+recordsCountCounterValue));
		}
	}

}
